
interface I{
  once:(event:string,cb:Function)=>void  //触发一次订阅
  on: (event:string,fn:Function)=>void  //订阅
  off: (event:string,cb:Function)=>void //删除
  emit: (event:string,...args:any[])=>void //派发
}

//监听器
class Emitter implements I {

  events: Map<string,Function[]>
  constructor(){
    this.events = new Map();
  }
  once(event:string,cb:Function): void {
    // 实现触发一次订阅的方法
    //创建一个自定义函数，通过on触发，触发后立马通知off()
    const callback = (...args:any[])=>{
      cb(...args)
      this.off(event,callback);
    }
    this.on(event,callback)

  }
  
  on(event:string,cb:Function): void {
    // 实现订阅方法
    if(this.events.has(event)){
      //map中有事件
      const cbList = this.events.get(event)
      cbList && cbList.push(cb)
    }else{
      this.events.set(event,[cb])
    }
  }
  
  off(event:string,cb:Function): void {
    // 实现删除订阅方法
    const cbList = this.events.get(event)
    if(cbList){
      //有事件
      const list = cbList.filter(fn => fn !== cb)
      if(list.length > 0){
        this.events.set(event,list)
      }else{
        this.events.delete(event)
      }
    }else{
      this.events.delete(event)
    }
    
  }
  
  emit(event:string,...args:any[]): void {
    // 实现派发方法
    const cbList = this.events.get(event)
    console.log(cbList);
    cbList && cbList.forEach(fn => {
      fn(...args)
    })
  }
}

const bus = new Emitter()
// bus.on('msg',()=>{
//   console.log('点击了');
// })
const cb = (...args:any[])=>{
  console.log(...args,'111');
}
//bus.on('msg',cb)

//bus.emit('msg','你好')

//bus.off('msg',cb)

bus.once('message',cb)
bus.emit('message','hello')
console.log(bus);
